<template>
  <section class="main">
    <el-form ref="myFormRef" :model="formData" :rules="rules" label-width="0px" size="large">
      <h2>欢迎使用管理系统</h2>
      <el-form-item prop="mobile">
        <el-input v-model="formData.mobile" placeholder="请输入电话号码" maxlength="11" type="tel" clearable />
      </el-form-item>
      <el-form-item prop="password">
        <el-input v-model="formData.password" type="password" maxlength="21" placeholder="请输入密码" show-password />
      </el-form-item>
      <el-form-item prop="verificationCode">
        <el-input maxlength="4" placeholder="请输入图形验证码" v-model="formData.verificationCode">
          <template #suffix>
            <img :src="verificationCodePath" @click="handleChangeCode(myForm)" class="code-image" />
          </template>
        </el-input>
      </el-form-item>
      <el-form-item class="item-btns">
        <el-button type="primary" native-type="submit" @click.prevent="submitForm(myFormRef)">登录</el-button>
        <el-button type="primary" @click="resetForm(myFormRef)">清空</el-button>
      </el-form-item>
    </el-form>
  </section>
</template>

<script setup lang="ts">
import { reactive, ref,onActivated } from "vue";
import { useRouter } from "vue-router";
import { useStore } from "vuex";
import { Md5 } from "ts-md5";
import request from "@/utils/request";

import type { FormInstance, FormRules } from "element-plus";
const myFormRef = ref<FormInstance>();

// 登录表单的参数
const formData = reactive({
  mobile: "",
  password: "",
  verificationCode: "",
  uuid: ""
});

const verificationCodePath = ref("");

const handleChangeCode = () => {
  request({ url: "/login/verificationCode" }).then((res) => {
    if (res.data.code >= 1) {
      formData.uuid = res.data.data.uuid;
      verificationCodePath.value = res.data.data.codeImage;
    }
  });
};

// 定义表单校验规则
const rules = reactive<FormRules>({
  mobile: [
    { required: true, message: "请输入手机号码", trigger: "blur" },
    { min: 11, max: 11, message: "手机号码必须是11位", trigger: "blur" },
  ],
  password: [
    { required: true, message: "请输入密码", trigger: "blur" },
    { min: 6, max: 19, message: "请输入6到19位密码", trigger: "blur" },
  ],
  verificationCode: [
    { required: true, message: "请输入验证码", trigger: "blur" },
  ],
});

// 使用路由
const router = useRouter();
// 使用状态管理（Vuex）
const store = useStore();

/**
 * 点击登录按钮
 * @param myFormRef 
 */
const submitForm = (myFormRef: FormInstance) => {
  // validate：校验表单
  myFormRef.validate((valid) => {
    // 校验失败
    if (!valid) {
      return;
    }

    // 拷贝一个formData中的数据，避免把密码加密后密码框内容发生变化
    const data = {
      ...formData,
    };
    // md5加密
    data.password = Md5.hashStr(data.password);
    // 发起异步请求
    request({ url: "/login/adminLogin", data, method: "post" }).then((res) => {
      // 登录成功
      if (res.data.code > 0) {
        window.alert("登录成功");

        // 将数据存入Vuex
        store.commit("setAdmin", res.data.data);

        // 跳转到首页
        router.push("/home");
      }
    }, () => {
      window.alert("登录失败");
    });
  });
};

/**
 * 重置表单内容
 * @param myFormRef 
 */
const resetForm = (myFormRef: FormInstance) => {
  if (myFormRef) {
    myFormRef.resetFields();
  }
};

onActivated(() => {
    handleChangeCode();
})

</script>

<style scoped lang="scss">
.main {
  background-color: #333333;
  height: 100vh;

  .el-form {
    display: flex;
    flex-direction: column;
    background-color: #fff;
    border-radius: 20px;
    padding: 40px 60px;
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);
    width: 400px;
    margin: auto;

    h2 {
      padding: 10px;
      text-align: center;
    }
  }

  .code-row {
    display: flex;

    .code-input {
      margin-right: 20px;
    }
  }
}
</style>
<style>
.item-btns>.el-form-item__content {
  justify-content: center;
}
</style>